package com.mjk.common.web.getway.restful.prototal.ws.soap.proxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Objects;

public class BeeSoapClassLoader extends ClassLoader{
	private final File resourceFile;
	
	final ThreadLocal<String> fileName = new ThreadLocal<>();
	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		
		Class<?> clazz = super.loadClass(name);
		if(clazz!=null){
			return clazz;
		}
		clazz = findClass(fileName.get());
		return clazz;
	}
	
    public BeeSoapClassLoader(){
        // 获取当前class文件的包路径
        String basePath = Objects.requireNonNull(BeeSoapClassLoader.class.getResource("")).getPath();

        this.resourceFile = new File(basePath);
    }

    /**
     * 将class文件加载到JVM
     */
    @Override
    protected Class<?> findClass(String name) {
        // 获得包名拼接类名--->全限定名
    	fileName.set(name);
        String className = BeeSoapClassLoader.class.getPackage().getName() + "." + name;
        if(resourceFile != null){
            File classFile = new File(resourceFile,name.replace("\\.", "/") + ".class");
            if(classFile.exists()){

                try(  FileInputStream in = new FileInputStream(classFile);
                      ByteArrayOutputStream out = new ByteArrayOutputStream();){
                    byte [] buff = new byte[1024];
                    int len;
                    while ((len = in.read(buff)) != -1) {
                        out.write(buff, 0, len);
                    }
                    // 加载到JVM
                    return defineClass(className, out.toByteArray(), 0,out.size());
                }catch (Exception e) {
                   //do noting
                }
            }
        }
        return null;
    }
}
